package com.int_tech.user.controller;

import com.google.gson.Gson;
import com.int_tech.car.entity.Car;
import com.int_tech.car.service.CarService;
import com.int_tech.facility.entity.Facility;
import com.int_tech.power.service.PowerService;
import com.int_tech.station.dao.StationDao;
import com.int_tech.station.entity.Station;
import com.int_tech.station.service.StationService;
import com.int_tech.user.dao.ClientDao;
import com.int_tech.user.dao.UserDao;
import com.int_tech.user.entity.Client;
import com.int_tech.user.entity.User;
import com.int_tech.user.servise.UserService;
import com.int_tech.utils.*;
import com.int_tech.utils.poiOut.ClientPoi;
import com.int_tech.utils.poiOut.UserPoi;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by liubch on 2017/9/25.
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userservice;

    @Autowired
    private PowerService powerService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private ClientDao clientDao;

    @Autowired
    private CarService carService;

    @Autowired
    private StationService stationService;

    /**
     * 通过管理员id查询客户信息
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/clientUser", method = RequestMethod.GET)
    public String clientUser(Model model, HttpServletRequest request) {

        //通过超级管理员id查询客户列表
        List<User> userList = userDao.findByType(2);

        model.addAttribute("userList", userList);

        //查询公司列表
        List<Client> clientList = clientDao.findAll();

        model.addAttribute("clientList", clientList);


        return "/user/clientUser";
    }


    /**
     * 客户管理，客户信息管理
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/client", method = RequestMethod.GET)
    public String client(Model model, HttpServletRequest request) {

        //通过超级管理员id查询客户列表
        List<Client> clientList = clientDao.findAll();

        model.addAttribute("clientList", clientList);

        return "/user/client";
    }


    /**
     * 用户管理页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String user(Model model, HttpServletRequest request) {

        //通过超级管理员id查询客户列表
        //从session或者哪里获取当前登录者id，获取信息，暂时设置为京东
        //String clientId = "1";


        int clientId1 = -99;

        try
        {
            clientId1 = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }

        String clientId = String.valueOf(clientId1);
        List<User> userList = new ArrayList<>();
        List<User> clientUser = new ArrayList<>();

        if ("1".equals(clientId)) {
            userList = userDao.findByType(3);
            clientUser = userDao.findByType(2);
            userList.addAll(clientUser);
        } else {
            userList = userservice.findByClientIdAndType(clientId, 3);
            clientUser = userDao.findByClientIdAndType(clientId, 2);
            userList.addAll(clientUser);
        }

        model.addAttribute("userList", userList);


        List<Client> clients = clientDao.findAll();

        model.addAttribute("clients", clients);

        return "/user/user";
    }

    /**
     * 保存客戶信息
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/addClient", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addClient(HttpServletRequest request, String userJson) throws UnsupportedEncodingException, UnknownHostException {

        Client client = new Gson().fromJson(userJson, Client.class);
//        Client user1 = clientDao.findByNameAndLegalPerson(user.getName(), user.getLegalPerson());
//
//        User client = userDao.findById(1);

//        if (user1 == null) {
//            user.setCreateTime(new Date());
//            user.setType(2);
//            user.setPassword("123456");
//            user.setClientId("1");
//            user.setClientName(client.getName());
//        } else {
//            user.setId(user1.getId());
//            user.setType(user1.getType());
//            user.setPassword(user1.getPassword());
//            user.setClientId("1");
//            user.setUpdateTime(new Date());
//        }
        client.setCreateTime(new Date());
        client.setUpdateTime(new Date());
        Client client1 = clientDao.save(client);
        if (client1!=null){
            return "1";
        }
        return "0";
    }


    /**
     * 添加用户
     *
     * @param request
     * @param userJson
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String addUser(HttpServletRequest request, String userJson) throws UnsupportedEncodingException, UnknownHostException {

        User user = new Gson().fromJson(userJson, User.class);
        String a = "";
        int clientId = (int) request.getSession().getAttribute("uid");
        User user1= userDao.findOne(clientId);
//        User user1= userDao.findByClientName(user.getClientName());
        if (user1.getType()==1&&user.getType()==3){
            a="2";
            return a;
        }
        if (user1.getType()==2&&user.getType()==2){
            a="3";
            return a;
        }

        if(user.getType() == 3)
        {
            user.setClientId(String.valueOf(clientId));
        }
        else
        {
            Client client = clientDao.findByName(user.getClientName());
            user.setClientId(String.valueOf(client.getId()));
        }

//        user.setClientName(user1.getName());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        User save = userDao.save(user);
        if (save!=null){
            a="0";
        }else{
            a="1";
        }
        return a;
    }


    /**
     * 鉴权
     *
     * @param request
     * @param action
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/checkPower", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String checkPower(HttpServletRequest request, String action) throws UnsupportedEncodingException, UnknownHostException {

        //获取当前登录用户id
        int userId = (int) request.getSession().getAttribute("uid");

        Result result = powerService.checkPowerByUser(action, userId);

        JSONObject object = new JSONObject();

        if (result.getStatus() == 200) {
            object.put("status", "success");
        } else {
            object.put("status", "fail");
            object.put("msg", "当前用户没有该权限");
        }
        return object.toString();
    }


    /**
     * 用户登录页面
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, HttpServletRequest request) {

        return "/user/login";
    }

    /**
     * 用户信息页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public String userInfo(Model model, HttpServletRequest request) {

        String userinfo = (String) request.getSession().getAttribute("userInfoSession");

        User user = userDao.findUserByNameAndPassword(userinfo.split(",")[0], userinfo.split(",")[1]);

        model.addAttribute("user", user);

        String type = "";

        switch (user.getType()) {
            case 1:
                type = "超级管理员";
                break;
            case 2:
                type = "客户管理员";
                break;
            case 3:
                type = "普通用户";
                break;
        }

        model.addAttribute("type", type);

        return "/user/userinfo";
    }


    /**
     * 校验用户名密码
     *
     * @param request
     * @param username
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String checkPower(HttpServletRequest request, String username, String password) throws UnsupportedEncodingException, UnknownHostException {

//        User user = userDao.findUserByNameAndPasswordAndIsDel(username, password, 0);
        User user = userDao.findUserByNameAndPassword(username, password);
        JSONObject object = new JSONObject();
        if (user == null) {
            object.put("status", "fail");
            object.put("msg", "用户名或密码不正确");
        } else {
            //共享session接口获取存放
            object.put("status", "success");

            JSONObject jsonObject = new JSONObject();

            if (user.getType() == 1) {
                request.getSession().setAttribute("username", "admin");

                jsonObject.put("key1","username");
                jsonObject.put("value1","admin");

            } else if (user.getType() == 2) {
                request.getSession().setAttribute("username", "client");

                jsonObject.put("key1","username");
                jsonObject.put("value1","client");
            } else if (user.getType() == 3) {
                request.getSession().setAttribute("username", "user");

                jsonObject.put("key1","username");
                jsonObject.put("value1","user");
            }


            request.getSession().setAttribute("userInfoSession", username + "," + password);
//            request.getSession().setAttribute("clientId", user.getClientId());
            request.getSession().setAttribute("clientId", String.valueOf(user.getId()));
            request.getSession().setAttribute("uid", user.getId());

            jsonObject.put("key2","userInfoSession");
            jsonObject.put("value2",username + "," + password);

            jsonObject.put("key3","clientId");
            jsonObject.put("value3",String.valueOf(user.getId()));

            jsonObject.put("key4","uid");
            jsonObject.put("value4",user.getId());


            MulServerSocket.httpClientPost("http://39.104.171.185:8080/car_networking/user/saveOtherSession",jsonObject.toString());
//            MulServerSocket.httpClientPost("http://39.104.181.194:8080/car_networking/user/saveOtherSession",jsonObject.toString());

        }


        return object.toString();
    }


    /**
     * 存储session
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/saveOtherSession", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String saveOtherSession(HttpServletRequest request,@RequestBody String requestBody) throws UnsupportedEncodingException
    {

        String requestJson = "";
        requestJson = URLDecoder.decode(requestBody, "utf-8");
        requestJson = new String(requestJson.getBytes("ISO-8859-1"),"UTF-8");
        String data = requestJson;
        JSONObject object = JSONObject.fromObject(data);


        request.getSession().setAttribute((String)object.get("key1"), (String)object.get("value1"));
        request.getSession().setAttribute((String)object.get("key2"), (String)object.get("value2"));
//            request.getSession().setAttribute("clientId", user.getClientId());
        request.getSession().setAttribute((String)object.get("key3"), (String)object.get("value3"));
        request.getSession().setAttribute((String)object.get("key4"), (String)object.get("value4"));

        return null;

    }


    /**
     * 电子锁socket
     *
     * @throws IOException
     */
    @RequestMapping(value = "/run", method = RequestMethod.GET)
    public void start() throws IOException {
        MulServerSocket.start();
    }

    /**
     * 装载率socket
     *
     * @throws IOException
     */
    @RequestMapping(value = "/runRate", method = RequestMethod.GET)
    public void runRate() throws IOException {
        MulServerSocketRate.startRate();
    }

    /**
     * 修改密码
     */

    @RequestMapping("/updatePassword")
    public String updatePassword(String newPassword, HttpServletRequest request, RedirectAttributes attr) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        user.setPassword(newPassword);
        userDao.save(user);
        attr.addAttribute("param", newPassword);
        return "redirect:/user/userInfo2";
    }


    @RequestMapping(value = "/userInfo2", method = RequestMethod.GET)
    public String userInfo2(Model model, HttpServletRequest request, String param) {

        String userinfo = (String) request.getSession().getAttribute("userInfoSession");

        User user = userDao.findUserByNameAndPassword(userinfo.split(",")[0], param);

        model.addAttribute("user", user);

        String type = "";

        switch (user.getType()) {
            case 1:
                type = "超级管理员";
                break;
            case 2:
                type = "客户管理员";
                break;
            case 3:
                type = "普通用户";
                break;
        }

        model.addAttribute("type", type);
        request.getSession().setAttribute("userInfoSession", user.getName() + "," + param);
        request.getSession().setAttribute("clientId", user.getClientId());
        request.getSession().setAttribute("uid", user.getId());
        return "/user/userinfo";
    }

    /**
     * TODO 根据用户名和密码修改密码验证
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("password")
    @ResponseBody
    /**
     * 返回1信息为空
     * 返回2密码错误
     * 返回0密码正确
     */
    public String findUserByPassword(User user) {
        if (user.getName() == null || user.getPassword() == null) {
            return "1";
        }
        User user1 = userDao.findUserByNameAndPassword(user.getName(), user.getPassword());
        if (user1 == null) {
            return "2";
        }
        return "0";
    }

    /**
     * TODO 客户分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @GetMapping("getClient")
    public String getClient(@RequestParam(value = "page", defaultValue = "1") Integer page,
                            @RequestParam(value = "size", defaultValue = "10") Integer size,
                            Model model) {
        Page<Client> clientPage = userservice.findByClientId(page, size);
        List<Client> clientList = clientPage.getContent();
        model.addAttribute("word","");
        model.addAttribute("type","1");
        model.addAttribute("clientPage",clientPage);
        model.addAttribute("clientList", clientList);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", clientPage.getTotalPages());
        return "/user/client";
    }

    /**
     * TODO 分页用户
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
//    @PostMapping("getUser")
    @RequestMapping(value = "/getUser")
    public String getUser(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          String word,
                          Model model,HttpServletRequest request){
//        int clientId = (int) request.getSession().getAttribute("uid");
        int clientId = -99;

        try
        {
            clientId = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }
        User user = userDao.findOne(clientId);
        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<User> userPage = null;
        //超级管理员
        if (user.getType()==1){
            userPage = userservice.findUser(page,10);
        }else {
            userPage = userservice.findByClientId(String.valueOf(clientId),page,10);
        }
        List<User> userList = userPage.getContent();

        List<User> list = new ArrayList<>();

//        String word = "";

        if(StringUtils.isEmpty(word))
        {
            list = userList;
            model.addAttribute("maxSize", userPage.getTotalPages());
        }
        else
        {
            List<User> list1 = new ArrayList<>();
            for(User ca : userList)
            {
                if(ca.toString().contains(word))
                {
                    list1.add(ca);
                }
            }

            int ceil = (int) Math.ceil(list.size() / 10);
            list = WordListUtils.wordListUtils(size, page, list1);
            model.addAttribute("maxSize", ceil+1);
        }

        model.addAttribute("word","");
        model.addAttribute("type","1");
        model.addAttribute("userPage",userPage);
        model.addAttribute("userList", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);

        model.addAttribute("userType",user.getType());

        List<Client> clients = clientDao.findById(Integer.parseInt(user.getClientId()));
        model.addAttribute("clients",clients);

        pageRequest = new PageRequest(1 - 1, 20);
        Page<Car> carPage = null;
        //超级管理员
        if (user.getType() == 1) {
            carPage = carService.getCarByPageable(pageRequest);
        } else {
            carPage = carService.getCarByPageable(pageRequest, clientId);
            List<Station> stationByid = (List<Station>) stationService.findStationByClientId(clientId).getData();
            model.addAttribute("AllStation", stationByid);
            model.addAttribute("AllStationSize", stationByid.size());
        }

        return "/user/user";
    }

    /**
     * TODO 模糊分页
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @RequestMapping("chooseClient")
    public String chooseClient(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size,
                               @RequestParam(value = "word")String word,Model model){

        Page<Client> clientPage = userservice.findByClientId(page, size);
        List<Client> list1 = clientPage.getContent();
        List<Client> clientList = new ArrayList<>();
        for(Client ca : list1)
        {
            if(ca.toString().contains(word))
            {
                clientList.add(ca);
            }
        }
        int ceil = (int) Math.ceil(clientList.size() / 10);
        List<Client> list = WordListUtils.wordListUtils(size, page, clientList);
        model.addAttribute("word",word);
        model.addAttribute("clientList", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize",ceil+1);
        model.addAttribute("type","2");
        return "/user/client";
    }

    /**
     * TODO 模糊分页
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @RequestMapping("chooseUser")
    public String chooseUser(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size,
                             @RequestParam(value = "word")String word,Model model,HttpServletRequest request){

        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<User> userList = null;
        //超级管理员
        if (user.getType() == 1) {
            userList = (List<User>) userservice.findAllUser().getData();
        } else {
            userList = userservice.findByClientId(String.valueOf(clientId));
        }
        List<User> carWordList = new ArrayList<>();
        for (User ca : userList) {
            if (ca.toString().contains(word)) {
                carWordList.add(ca);
            }
        }
        int ceil = (int) Math.ceil(carWordList.size() / 10);
        List<Car> list = WordListUtils.wordListUtils(size, page, carWordList);
        model.addAttribute("word", word);
        model.addAttribute("userList", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", ceil + 1);
        model.addAttribute("type", "2");

        List<Station> stationByid = (List<Station>) stationService.findStationByClientId(clientId).getData();
        model.addAttribute("AllStation", stationByid);
        model.addAttribute("AllStationSize", stationByid.size());

        List<Client> clients = clientDao.findById(Integer.parseInt(user.getClientId()));
        model.addAttribute("clients",clients);
        return "/user/user";
    }

    /**
     * TODO 删除客户
     * @param
     * @return
     * @author dmy
     */
    @PostMapping("deleteClient")
    @ResponseBody
    public String deleteClient(String order){
        Integer  id = Integer.valueOf(order);
        Client client = clientDao.findOne(id);
        client.setUpdateTime(new Date());
        client.setIsDel(CarEnum.OFF.getCode());
        Client save = clientDao.save(client);
        if (save!=null){
            return "0";
        }
        return "1";
    }

    /**
     * TODO 删除用户
     * @param
     * @return
     * @author dmy
     */
    @PostMapping("deleteUser")
    @ResponseBody
    public String deleteUser(String order2){
        Integer  id2 = Integer.valueOf(order2);
        User user = userDao.findOne(id2);
        user.setUpdateTime(new Date());
        user.setIsDel(CarEnum.OFF.getCode());
        User save = userDao.save(user);
        if (save!=null){
            return "0";
        }
        return "1";
    }
    /**
     * 修改客戶信息
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/updateClient", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String updateClient(HttpServletRequest request, String userJson) throws UnsupportedEncodingException, UnknownHostException {

        Client client = new Gson().fromJson(userJson, Client.class);
        client.setUpdateTime(new Date());
        Client client1 = clientDao.save(client);
        if (client1!=null){
            return "1";
        }
        return "0";
    }

    /**
     * 修改用户
     *
     * @param request
     * @param userJson
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/updateUser", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String updateUser(HttpServletRequest request, String userJson) throws UnsupportedEncodingException, UnknownHostException {

        User user = new Gson().fromJson(userJson, User.class);
        int clientId = (int) request.getSession().getAttribute("uid");
        User user1= userDao.findOne(clientId);
        String a = "";
//        if (user1.getType()==1&&user.getType()==3){
//            a="2";
//            return a;
//        }
        if (user1.getType()==2&&user.getType()==2){
            a="3";
            return a;
        }
        user.setClientId(String.valueOf(clientId));
        if (user1.getType()==1){
            User one = userDao.findOne(user.getId());
            user.setClientId(one.getClientId());
        }

        user.setUpdateTime(new Date());
        User save = userDao.save(user);
        if (save!=null){
            a="0";
        }else{
            a="1";
        }
        return a;
    }

    @RequestMapping("getClientById")
    @ResponseBody
    public Client getClientById(Integer id){
        Client client = clientDao.findOne(id);
        return client;
    }

    /**
     * TODO
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("getUserById")
    @ResponseBody
    public User getUserById(Integer id){
        User user = userDao.findOne(id);
        return user;
    }

    /**
     * TODO ex导出
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("userExout")
    public void exOut(HttpServletResponse response,@RequestParam(value = "word") String word, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<User> usersList = null;
        List<User> list = new ArrayList<>();
        if (word == ""&&word==null) {
            list = userDao.findByClientIdAndIsDel(String.valueOf(clientId), CarEnum.ON.getCode());
        } else {
            if (user.getType() == 1) {
                usersList = userDao.findUserByIsDel(CarEnum.ON.getCode());
            } else {
                usersList = userDao.findByClientIdAndIsDel(String.valueOf(clientId), CarEnum.ON.getCode());
            }
            for (User ca : usersList) {
                if (ca.toString().contains(word)) {
                    list.add(ca);
                }
            }
        }
        UserPoi.userPoi(list, response);
    }

    /**
     * TODO ex导出
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("clientExout")
    public void exOutClient(HttpServletResponse response,@RequestParam(value = "word") String word, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<Client> clientList = null;
        List<Client> list = new ArrayList<>();
        if (word == ""&&word==null) {
            list = clientDao.findByIsDel(CarEnum.ON.getCode());
        } else {
            clientList = clientDao.findByIsDel(CarEnum.ON.getCode());
            for (Client ca : clientList) {
                if (ca.toString().contains(word)) {
                    list.add(ca);
                }
            }
        }
        ClientPoi.clientPoi(list, response);
    }
}